import os
import jsonpath
from xmind_to_excel_case.exceltool import ExcelTool
from xmindparser import xmind_to_dict
from xmind_to_excel_case import settings


class ExcelCase:
    def __init__(self, **kwargs):
        self.xmind_path = os.path.join(settings.STATIC_PATH, kwargs.get("xmind_name"))  # xmind绝对路径
        self.excel_path = os.path.join(settings.STATIC_PATH, kwargs.get("excel_name"))  # excel绝对路径
        self.demand_id = kwargs.get("demand_id")  # 需求id
        self.write_data = []  # 将要写入的数据
        self.titles = [
            {
                "case_name": "用例名称",
                "demand_id": "需求ID",
                "precondition": "前置条件",
                "case_step": "用例步骤",
                "expected": "预期结果",
                "case_type": "用例类型",
                "case_status": "用例状态",
                "level": "用例等级",
                "founder": "创建人",
            }
        ]  # 表头
        self.keys = [
            "case_name",
            "demand_id",
            "precondition",
            "case_step",
            "expected",
            "case_type",
            "case_status",
            "level",
            "founder",
        ]  # key列表，用于规范写入顺序
        self.xmind_data = {}
        self.case_data = {}
        self.stop_title = ["步骤", "前置", "断言", "级别"]
        self.demand_name = "分类页增加品牌筛选条件"  # 需求名称

    # jsonpath取值的二次封装（最终封装会分离到合适的类去，到时继承该类即可）
    def get_path_data(self, res, path, status=False):
        """
        :param res: 响应值
        :param path: jsonpath字符串
        :param status: True:不做处理，直接返回（取到多个值适用）  False：取0号索引（取到单个值适用）
        :return: 获取的值
        """
        dt = jsonpath.jsonpath(res, path)
        if status:
            data = dt if dt else []
        else:
            data = dt[0] if dt else None
        return data

    # 读取 xmind 数据
    def read_xmind(self):
        self.xmind_data = xmind_to_dict(self.xmind_path)

    # 数据处理
    def recursive_data(self, xmind_data):
        if isinstance(xmind_data, list):
            for item in xmind_data:
                self.recursive_data(item)
        else:
            case_name = xmind_data.get("case_name", "")
            title = xmind_data.get("title", "")
            topic = xmind_data.get("topic", {})
            topics = xmind_data.get("topics", [])
            if title in self.stop_title:
                lis = []
                for item in topics:
                    topic = self.get_path_data(item, "$.topics..title", status=True)
                    topic = [f"    {tp}\n" for tp in topic]
                    tls = "\n".join([item.get("title"), "".join(topic)])
                    lis.append(tls)

                titles = "".join(lis)
                if self.case_data.get(case_name):
                    case_data = self.case_data[case_name]
                else:
                    case_data = {}
                    self.case_data[case_name] = case_data
                case_data[title] = titles
                return
            if topic:
                self.recursive_data(topic)
                return
            if topics and title != self.demand_name:
                case_name = " - ".join([case_name, title]) if case_name else title
            for item2 in topics:
                if case_name:
                    item2["case_name"] = case_name
                self.recursive_data(item2)

    # 用例数据合成
    def data_synthesis(self):
        lis = []
        for case_name in self.case_data:
            value = self.case_data.get(case_name)
            # status = value.get("status")
            # if status:continue
            if "到家活动手动结束/删除后再次导入" in case_name: continue
            level = value.get("级别")
            if level == "P0":
                lis.append(level)
            dt = {
                "case_name": case_name.replace("促销中台秒杀 - ", ""),
                "demand_id": self.demand_id,
                "precondition": value.get("前置"),
                "case_step": value.get("步骤"),
                "expected": value.get("断言"),
                "case_type": "功能测试",
                "case_status": "正常",
                "level": value.get("级别", "P1"),
                "founder": "user",
            }
            self.write_data.append(dt)

    # 写入excel
    def write_excel(self):
        obj = ExcelTool(self.excel_path, self.write_data, status=True, titles=self.titles, keys=self.keys,
                        static_path=None)
        obj.run()

    def run(self):
        self.read_xmind()
        self.recursive_data(self.xmind_data)
        self.data_synthesis()
        self.write_excel()


if __name__ == '__main__':
    kwargs = {
        "xmind_name": "搜索输入交互优化.xmind",
        "excel_name": "搜索输入交互优化.xlsx",
        "demand_id": 871801051,  # 需求id
    }
    obj = ExcelCase(**kwargs)
    obj.run()
    print("处理完毕")
